<?php

namespace app\forms\position;

use yii\db\Exception;
use app\models\Position;
use yii\web\HttpException;
use app\helpers\ArrayHelper;

/**
 * 岗位 创建
 */
class CreateForm extends BaseForm
{

    public $setDefault = 0;

    public function rules()
    {
        $rules = parent::rules();
        return array_merge($rules, [
            ['setDefault', 'boolean'],
        ]);
    }

    /**
     * @param $param
     * @throws HttpException
     */
    public static function create($param)
    {
        $form = new self();
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';
        try {

            $attr = ArrayHelper::humpToUnderline($form->getAttributes());
            unset($attr['item'], $attr['auth']);

            // 岗位
            $position = new Position;
            $position->setAttributes($attr);
            $position->save();

            // 权限
            $position->addItem($form->item, $form->auth, $form->data);

            if ($form->setDefault)
                $position->addDefaultItem($form->item, $form->auth, $form->data);

        } catch (Exception $e) {
            $form->serverError();
        }

        $form->createOk();
    }
}